
<!DOCTYPE html>
<html lang="">


<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0, user-scalable=no">
  <meta name="theme-color" content="#202020">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  <script src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" async></script>
  
  
    <meta name="keywords" content>
  

  
    <meta name="description" content="Go语言之时间包">
  
  
  
  <link rel="icon" type="image/x-icon" href="/images/footer-logo.png">
  
  <title>Go语言之时间包 [ 51AIOps 专注于运维自动化  微信： kaipython ]</title>
  
    <!-- stylesheets list from config.yml -->
    
      <link rel="stylesheet" href="//cdn.bootcss.com/pure/1.0.0/pure-min.css">
    
      <link rel="stylesheet" href="/css/xoxo.css">
    
  
</head>


<body>
  <div class="nav-container">
    <nav class="home-menu pure-menu pure-menu-horizontal">
  <a class="pure-menu-heading" href="/">
    
    <span class="title" style="text-transform:none">51AIOps 专注于运维自动化  微信： kaipython</span>
  </a>

  <ul class="pure-menu-list clearfix">
      
          
            
              <li class="pure-menu-item"><a href="/" class="pure-menu-link">首页</a></li>
            
          
      
  </ul>
   
</nav>

  </div>

  <div class="container" id="content-outer">
    <div class="inner" id="content-inner" style='margin-left:-68px!important'>
      <div class="post-container">
  <article class="post" id="post">
    <header class="post-header text-center">
      <h1 class="title">
        Go语言之时间包
      </h1>
      <span>
        
        <time class="time" datetime="2020-09-28T16:00:00.000Z">
        2020-09-29
      </time>
        
      </span>
      <span class="slash">/</span>
      <span class="post-meta">
      <span class="post-tags">
        
      </span>
    </span>
      <span class="slash">/</span>
      <span class="read">
      <span id="busuanzi_value_page_pv"></span> 点击
    </span>
      <span class="slash">/</span>
    </header>

    <div class="post-content">
      <h2 id="Go语言之时间包"><a href="#Go语言之时间包" class="headerlink" title="Go语言之时间包"></a>Go语言之时间包</h2><p>时间和日期是我们编程中经常会用到的，本文主要介绍了Go语言内置的time包的基本用法。</p>
<h1 id="time包"><a href="#time包" class="headerlink" title="time包"></a>time包</h1><p>time包提供了时间的显示和测量用的函数。日历的计算采用的是公历。</p>
<h4 id="1-时间类型"><a href="#1-时间类型" class="headerlink" title="1.时间类型"></a>1.时间类型</h4><p><code>time.Time</code>类型表示时间。我们可以通过<code>time.Now()</code>函数获取当前的时间对象，然后获取时间对象的年月日时分秒等信息。示例代码如下：</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">timeDemo</span><span class="params">()</span></span> &#123;</span><br><span class="line">	now := time.Now() <span class="comment">//获取当前时间</span></span><br><span class="line">	fmt.Printf(<span class="string">"current time:%v\n"</span>, now)</span><br><span class="line"></span><br><span class="line">	year := now.Year()     <span class="comment">//年</span></span><br><span class="line">	month := now.Month()   <span class="comment">//月</span></span><br><span class="line">	day := now.Day()       <span class="comment">//日</span></span><br><span class="line">	hour := now.Hour()     <span class="comment">//小时</span></span><br><span class="line">	minute := now.Minute() <span class="comment">//分钟</span></span><br><span class="line">	second := now.Second() <span class="comment">//秒</span></span><br><span class="line">	fmt.Printf(<span class="string">"%d-%02d-%02d %02d:%02d:%02d\n"</span>, year, month, day, hour, minute, second)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="2-时间戳"><a href="#2-时间戳" class="headerlink" title="2.时间戳"></a>2.时间戳</h4><p>时间戳是自1970年1月1日（08:00:00GMT）至当前时间的总毫秒数。它也被称为Unix时间戳（UnixTimestamp）。</p>
<p>基于时间对象获取时间戳的示例代码如下：</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">timestampDemo</span><span class="params">()</span></span> &#123;</span><br><span class="line">	now := time.Now()            <span class="comment">//获取当前时间</span></span><br><span class="line">	timestamp1 := now.Unix()     <span class="comment">//时间戳</span></span><br><span class="line">	timestamp2 := now.UnixNano() <span class="comment">//纳秒时间戳</span></span><br><span class="line">	fmt.Printf(<span class="string">"current timestamp1:%v\n"</span>, timestamp1)</span><br><span class="line">	fmt.Printf(<span class="string">"current timestamp2:%v\n"</span>, timestamp2)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>使用<code>time.Unix()</code>函数可以将时间戳转为时间格式。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">timestampDemo2</span><span class="params">(timestamp <span class="keyword">int64</span>)</span></span> &#123;</span><br><span class="line">	timeObj := time.Unix(timestamp, <span class="number">0</span>) <span class="comment">//将时间戳转为时间格式</span></span><br><span class="line">	fmt.Println(timeObj)</span><br><span class="line">	year := timeObj.Year()     <span class="comment">//年</span></span><br><span class="line">	month := timeObj.Month()   <span class="comment">//月</span></span><br><span class="line">	day := timeObj.Day()       <span class="comment">//日</span></span><br><span class="line">	hour := timeObj.Hour()     <span class="comment">//小时</span></span><br><span class="line">	minute := timeObj.Minute() <span class="comment">//分钟</span></span><br><span class="line">	second := timeObj.Second() <span class="comment">//秒</span></span><br><span class="line">	fmt.Printf(<span class="string">"%d-%02d-%02d %02d:%02d:%02d\n"</span>, year, month, day, hour, minute, second)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="3-时间间隔"><a href="#3-时间间隔" class="headerlink" title="3.时间间隔"></a>3.时间间隔</h4><p><code>time.Duration</code>是<code>time</code>包定义的一个类型，它代表两个时间点之间经过的时间，以纳秒为单位。<code>time.Duration</code>表示一段时间间隔，可表示的最长时间段大约290年。</p>
<p>time包中定义的时间间隔类型的常量如下：</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> (</span><br><span class="line">    Nanosecond  Duration = <span class="number">1</span></span><br><span class="line">    Microsecond          = <span class="number">1000</span> * Nanosecond</span><br><span class="line">    Millisecond          = <span class="number">1000</span> * Microsecond</span><br><span class="line">    Second               = <span class="number">1000</span> * Millisecond</span><br><span class="line">    Minute               = <span class="number">60</span> * Second</span><br><span class="line">    Hour                 = <span class="number">60</span> * Minute</span><br><span class="line">)</span><br></pre></td></tr></table></figure>

<p>例如：<code>time.Duration</code>表示1纳秒，<code>time.Second</code>表示1秒。</p>
<h4 id="4-时间操作"><a href="#4-时间操作" class="headerlink" title="4.时间操作"></a>4.时间操作</h4><h5 id="Add"><a href="#Add" class="headerlink" title="Add"></a>Add</h5><p>我们在日常的编码过程中可能会遇到要求时间+时间间隔的需求，Go语言的时间对象有提供Add方法如下：</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="params">(t Time)</span> <span class="title">Add</span><span class="params">(d Duration)</span> <span class="title">Time</span></span></span><br></pre></td></tr></table></figure>

<p>举个例子，求一个小时之后的时间：</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">	now := time.Now()</span><br><span class="line">	later := now.Add(time.Hour) <span class="comment">// 当前时间加1小时后的时间</span></span><br><span class="line">	fmt.Println(later)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h5 id="Sub"><a href="#Sub" class="headerlink" title="Sub"></a>Sub</h5><p>求两个时间之间的差值：</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="params">(t Time)</span> <span class="title">Sub</span><span class="params">(u Time)</span> <span class="title">Duration</span></span></span><br></pre></td></tr></table></figure>

<p>返回一个时间段t-u。如果结果超出了Duration可以表示的最大值/最小值，将返回最大值/最小值。要获取时间点t-d（d为Duration），可以使用t.Add(-d)。</p>
<h5 id="Equal"><a href="#Equal" class="headerlink" title="Equal"></a>Equal</h5><figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="params">(t Time)</span> <span class="title">Equal</span><span class="params">(u Time)</span> <span class="title">bool</span></span></span><br></pre></td></tr></table></figure>

<p>判断两个时间是否相同，会考虑时区的影响，因此不同时区标准的时间也可以正确比较。本方法和用t==u不同，这种方法还会比较地点和时区信息。</p>
<h5 id="Before"><a href="#Before" class="headerlink" title="Before"></a>Before</h5><figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="params">(t Time)</span> <span class="title">Before</span><span class="params">(u Time)</span> <span class="title">bool</span></span></span><br></pre></td></tr></table></figure>

<p>如果t代表的时间点在u之前，返回真；否则返回假。</p>
<h5 id="After"><a href="#After" class="headerlink" title="After"></a>After</h5><figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="params">(t Time)</span> <span class="title">After</span><span class="params">(u Time)</span> <span class="title">bool</span></span></span><br></pre></td></tr></table></figure>

<p>如果t代表的时间点在u之后，返回真；否则返回假。</p>
<h4 id="5-时间格式化"><a href="#5-时间格式化" class="headerlink" title="5.时间格式化"></a>5.时间格式化</h4><p>时间类型有一个自带的方法<code>Format</code>进行格式化，需要注意的是Go语言中格式化时间模板不是常见的<code>Y-m-d H:M:S</code>而是使用Go的诞生时间2006年1月2号15点04分（记忆口诀为2006 1 2 3 4）。也许这就是技术人员的浪漫吧。</p>
<p>补充：如果想格式化为12小时方式，需指定<code>PM</code>。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">formatDemo</span><span class="params">()</span></span> &#123;</span><br><span class="line">	now := time.Now()</span><br><span class="line">	<span class="comment">// 格式化的模板为Go的出生时间2006年1月2号15点04分 Mon Jan</span></span><br><span class="line">	<span class="comment">// 24小时制</span></span><br><span class="line">	fmt.Println(now.Format(<span class="string">"2006-01-02 15:04:05.000 Mon Jan"</span>))</span><br><span class="line">	<span class="comment">// 12小时制</span></span><br><span class="line">	fmt.Println(now.Format(<span class="string">"2006-01-02 03:04:05.000 PM Mon Jan"</span>))</span><br><span class="line">	fmt.Println(now.Format(<span class="string">"2006/01/02 15:04"</span>))</span><br><span class="line">	fmt.Println(now.Format(<span class="string">"15:04 2006/01/02"</span>))</span><br><span class="line">	fmt.Println(now.Format(<span class="string">"2006/01/02"</span>))</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="6-解析字符串格式的时间"><a href="#6-解析字符串格式的时间" class="headerlink" title="6.解析字符串格式的时间"></a>6.解析字符串格式的时间</h4><figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">now := time.Now()</span><br><span class="line">fmt.Println(now)</span><br><span class="line"><span class="comment">// 加载时区</span></span><br><span class="line">loc, err := time.LoadLocation(<span class="string">"Asia/Shanghai"</span>)</span><br><span class="line"><span class="keyword">if</span> err != <span class="literal">nil</span> &#123;</span><br><span class="line">	fmt.Println(err)</span><br><span class="line">	<span class="keyword">return</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// 按照指定时区和指定格式解析字符串时间</span></span><br><span class="line">timeObj, err := time.ParseInLocation(<span class="string">"2006/01/02 15:04:05"</span>, <span class="string">"2019/08/04 14:15:20"</span>, loc)</span><br><span class="line"><span class="keyword">if</span> err != <span class="literal">nil</span> &#123;</span><br><span class="line">	fmt.Println(err)</span><br><span class="line">	<span class="keyword">return</span></span><br><span class="line">&#125;</span><br><span class="line">fmt.Println(timeObj)</span><br><span class="line">fmt.Println(timeObj.Sub(now))</span><br></pre></td></tr></table></figure>


    </div>

  </article>
  <div class="toc-container">
    
  <div id="toc" class="toc-article">
    <strong class="toc-title">目录</strong>
    <ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#Go语言之时间包"><span class="toc-text">Go语言之时间包</span></a></li></ol><li class="toc-item toc-level-1"><a class="toc-link" href="#time包"><span class="toc-text">time包</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#1-时间类型"><span class="toc-text">1.时间类型</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#2-时间戳"><span class="toc-text">2.时间戳</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#3-时间间隔"><span class="toc-text">3.时间间隔</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#4-时间操作"><span class="toc-text">4.时间操作</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#Add"><span class="toc-text">Add</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#Sub"><span class="toc-text">Sub</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#Equal"><span class="toc-text">Equal</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#Before"><span class="toc-text">Before</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#After"><span class="toc-text">After</span></a></li></ol></li><li class="toc-item toc-level-4"><a class="toc-link" href="#5-时间格式化"><span class="toc-text">5.时间格式化</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#6-解析字符串格式的时间"><span class="toc-text">6.解析字符串格式的时间</span></a></li></ol></li>
  </div>


  </div>
</div>
<script type="text/javascript" src="//rf.revolvermaps.com/0/0/8.js?i=5sr5du46f27&amp;m=0&amp;c=ff0000&amp;cr1=ffffff&amp;f=arial&amp;l=33" async="async"></script>
<div class="copyright">
    <span>本作品采用</span>
    <a href="https://creativecommons.org/licenses/by/4.0/">知识共享署名 4.0 国际许可协议</a>
    <span>进行许可。 转载时请注明原文链接。</span>
</div>


  
    <div class="post-nav" style="margin-left:-168px;">
      <div class="post-nav-item post-nav-next">
        
          <span>〈 </span>
          <a href="/2020/09/15/容器技术真的是银弹吗/" rel="next" title="容器技术真的是银弹吗？">
          容器技术真的是银弹吗？
          </a>
        
      </div>
  
      <div class="post-nav-item post-nav-prev">
          
          <a href="/2020/09/29/Go语言之指针/" rel="prev" title="Go语言之指针">
            Go语言之指针
          </a>
          <span>〉</span>
        
      </div>
    </div>
  


	
	<div style="width:109%; margin-left:-144px" id="lv-container" data-id="city" data-uid="MTAyMC80OTg5NS8yNjM4Ng==">
	<script type="text/javascript">
   	   (function(d, s) {
       		var j, e = d.getElementsByTagName(s)[0];

       		if (typeof LivereTower === 'function') { return; }

       		j = d.createElement(s);
       		j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
       		j.async = true;

       		e.parentNode.insertBefore(j, e);
   	   })(document, 'script');
	</script>
	<noscript> 为正常使用来必力评论功能请激活JavaScript</noscript>
        </div>
	



    </div>

    

  </div>
  <footer class="footer text-center">
    <div id="bottom-inner">
        <a class="bottom-item" href target="_blank">GitHub</a> |
        <a class="bottom-item" href>友情链接</a> |
        <a class="bottom-item" href="https://hexo.io" target="_blank">Powered by hexo</a> |
        <a class="bottom-item" href="https://github.com/fooying/hexo-theme-xoxo-plus" target="_blank">Theme xoxo-plus</a> |
        <a class="bottom-item" href="/atom.xml">订阅</a>
    </div>
</footer>

  

<script>
  (function(window, document, undefined) {

    var timer = null;

    function returnTop() {
      cancelAnimationFrame(timer);
      timer = requestAnimationFrame(function fn() {
        var oTop = document.body.scrollTop || document.documentElement.scrollTop;
        if (oTop > 0) {
          document.body.scrollTop = document.documentElement.scrollTop = oTop - 50;
          timer = requestAnimationFrame(fn);
        } else {
          cancelAnimationFrame(timer);
        }
      });
    }

    var hearts = [];
    window.requestAnimationFrame = (function() {
      return window.requestAnimationFrame ||
        window.webkitRequestAnimationFrame ||
        window.mozRequestAnimationFrame ||
        window.oRequestAnimationFrame ||
        window.msRequestAnimationFrame ||
        function(callback) {
          setTimeout(callback, 1000 / 60);
        }
    })();
    init();

    function init() {
      css(".heart{z-index:9999;width: 10px;height: 10px;position: fixed;background: #f00;transform: rotate(45deg);-webkit-transform: rotate(45deg);-moz-transform: rotate(45deg);}.heart:after,.heart:before{content: '';width: inherit;height: inherit;background: inherit;border-radius: 50%;-webkit-border-radius: 50%;-moz-border-radius: 50%;position: absolute;}.heart:after{top: -5px;}.heart:before{left: -5px;}");
      attachEvent();
      gameloop();
      addMenuEvent();
    }

    function gameloop() {
      for (var i = 0; i < hearts.length; i++) {
        if (hearts[i].alpha <= 0) {
          document.body.removeChild(hearts[i].el);
          hearts.splice(i, 1);
          continue;
        }
        hearts[i].y--;
        hearts[i].scale += 0.004;
        hearts[i].alpha -= 0.013;
        hearts[i].el.style.cssText = "left:" + hearts[i].x + "px;top:" + hearts[i].y + "px;opacity:" + hearts[i].alpha + ";transform:scale(" + hearts[i].scale + "," + hearts[i].scale + ") rotate(45deg);background:" + hearts[i].color;
      }
      requestAnimationFrame(gameloop);
    }

    /**
     * 给logo设置点击事件
     * 
     * - 回到顶部
     * - 出现爱心
     */
    function attachEvent() {
      var old = typeof window.onclick === "function" && window.onclick;
      var logo = document.getElementById("logo");
      if (logo) {
        logo.onclick = function(event) {
          returnTop();
          old && old();
          createHeart(event);
        }
      }
      
    }

    function createHeart(event) {
      var d = document.createElement("div");
      d.className = "heart";
      hearts.push({
        el: d,
        x: event.clientX - 5,
        y: event.clientY - 5,
        scale: 1,
        alpha: 1,
        color: randomColor()
      });
      document.body.appendChild(d);
    }

    function css(css) {
      var style = document.createElement("style");
      style.type = "text/css";
      try {
        style.appendChild(document.createTextNode(css));
      } catch (ex) {
        style.styleSheet.cssText = css;
      }
      document.getElementsByTagName('head')[0].appendChild(style);
    }

    function randomColor() {
      // return "rgb(" + (~~(Math.random() * 255)) + "," + (~~(Math.random() * 255)) + "," + (~~(Math.random() * 255)) + ")";
      return "#F44336";
    }

    function addMenuEvent() {
      var menu = document.getElementById('menu-main-post');
      if (menu) {
        var toc = document.getElementById('toc');
        if (toc) {
          menu.onclick = function() {
            if (toc) {
              if (toc.style.display == 'block') {
                toc.style.display = 'none';
              } else {
                toc.style.display = 'block';
              }
            }
          };
        } else {
          menu.style.display = 'none';
        }
      }
    }

  })(window, document);
</script>

  



  

</body>
</html>
